package net.gazhi.delonix.grac.web;

import java.util.Collection;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import net.gazhi.delonix.core.entity.LoginUser;
import net.gazhi.delonix.core.thread.ThreadContext;
import net.gazhi.delonix.core.web.RequestMappingHandlerMappingHolder;
import net.gazhi.delonix.grac.entity.act.MenuItem;
import net.gazhi.delonix.grac.service.ActionAuthorizationService;

import org.springframework.web.method.HandlerMethod;

public class Functions {

	@SuppressWarnings("rawtypes")
	public static Set keySet(Map map) {
		return map == null ? null : map.keySet();
	}

	public static String lang(String zh, String en) {
		Locale locale = loginUser().getLocale();
		return Locale.CHINESE.equals(locale) || Locale.SIMPLIFIED_CHINESE.equals(locale) || Locale.TRADITIONAL_CHINESE.equals(locale) ? zh : en;
	}

	/**
	 * 判断路径的权限<br>
	 * 映射的绝对路径(例如 /grac/role/delete 不包含context名字)
	 * 
	 * @param uriPattern
	 * @return
	 */
	public static boolean isAuthorized(String uriPattern) {
		ActionAuthorizationService actionAuthorizationService = ThreadContext.getBean(ActionAuthorizationService.class);
		RequestMappingHandlerMappingHolder mpHolder = ThreadContext.getBean(RequestMappingHandlerMappingHolder.class);
		HandlerMethod hm = mpHolder.machMethod(uriPattern);
		return hm == null ? false : actionAuthorizationService.isAuthorized(hm);
	}

	public static Set<MenuItem> authorizedRootMenuItems(String menuUsage) {
		ActionAuthorizationService actionAuthorizationService = ThreadContext.getBean(ActionAuthorizationService.class);
		return actionAuthorizationService.listAuthorizedRootMenuItems(menuUsage);
	}

	public static boolean isGuest() {
		return loginUser().getId() < 0;
	}

	public static LoginUser loginUser() {
		return ThreadContext.getLoginUser();
	}

	public static boolean contains(Collection<?> objs, Object obj) {
		return objs != null && objs.contains(obj);
	}

}
